/*
 * @Author: wangdian
 * @Date: 2023-08-15 11:06:19
 * @LastEditors: wangdian
 * @LastEditTime: 2023-08-16 10:18:23
 * @Description: file content
 * @FilePath: \workspace\websocket.js
 */

var ws = require("nodejs-websocket");

ws.createServer( (conn) =>{
    console.log("conn:" + conn);
    conn.on("text",  (str)=> {
        //服务端接收到的数据
        console.log("服务端收到:" + str);
        if (str.checked == 'foo') {
            
        }
        //接收到的数据再发送回客户端
        // conn.sendText(str);
        
    });
    const intervalId = setInterval(() => {
        var data = [
            {
                wxdh: "A1",
                num: '1',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            },
            {
                wxdh: "A1",
                num: '3',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            },
            { wxdh: "A1", num: '4', gzzt: "正在工作", tssj: "2023-8-14", ywjg: "有", jgjb: "1" },
            {
                wxdh: "A1",
                num: '1',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            }]
        for (var i = 0; i < data.length; i++) {
            console.log(i)
            data[i]['num'] = Math.floor(Math.random() * 100 + 1);
        }
        data = JSON.stringify(data)
        conn.send(data, () => {
            console.log('如果说后端想要监听发送状况，能走进来是否意味着发送成功')
        });
        console.log('conn.readyState', conn.readyState)   //ws状态
    }, 1000)

    conn.on("close", function (code, reason) {
        console.log("服务端监听到关闭连接.")
        clearInterval(intervalId);
    });

    conn.on("error", function (code, reason) {
        console.log("服务端监听到连接失败.")
    });

    conn.on("pong", function (res) {
        console.log(res)
    })
}).listen(8848);

